package com.eportal.action.background;

import com.eportal.action.BaseAction;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TOpenLog;
import com.eportal.service.TOpenLogService;
import com.eportal.util.DateUtils;
import com.framework.excelTools.ExcelUtil;
import com.framework.jqgrid.JqGridPager;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 开门日志管理
 * @author chencheng
 *
 */
public class TOpenLogAction extends BaseAction implements ModelDriven<TOpenLog> {

    /**
	 * @author chencheng
	 */
	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(TOpenLogAction.class.getName());

    private Map<String, Object> result = new HashMap<String, Object>();

    @Autowired
    TOpenLogService tOpenLogService;




    /**
     * 开门日志管理
     */
    public String listView() {
    	getRequest().setAttribute("userId", getRequest().getParameter("userId"));
    	getRequest().setAttribute("pid", getRequest().getParameter("pid"));
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	getRequest().setAttribute("userRole", userRole);
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	getRequest().setAttribute("rLevel", user.getrLevel());
        return SUCCESS;
    }

    /**
     * 开门日志列表
     */
    public void page() throws Exception {
        JqGridPager jqGridPager = new JqGridPager();
    	String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String cityCode = getRequest().getParameter("cityCode");
    	String ptimeStart1 = getRequest().getParameter("ptimeStart1");
    	String ptimeEnd1 = getRequest().getParameter("ptimeEnd1");
    	String userName = getRequest().getParameter("userName");
    	String type = getRequest().getParameter("type");
    	String cbName = getRequest().getParameter("cbName");
    	String tel = getRequest().getParameter("tel");
    	String userId = getRequest().getParameter("userId");
    	String pid = getRequest().getParameter("pid");

    	String where  = getWhere(agtCode,communityId,cityCode,ptimeStart1,ptimeEnd1,userName,type,cbName,tel,userId,pid);

    	jqGridPager.setWhere(where.toString());
        setPage(getRequest(), jqGridPager);
        List<Map<String, Object>> tOpenLog = tOpenLogService.list(jqGridPager);
        jqGridQueryMap(TOpenLog.class, getRequest(), tOpenLog, getResponse(), jqGridPager);
    }


    /**
     * 移动端显示开门日志
     * @return
     */
/*    public String listView4App() {
    	try{
    		log.info("----listView4App start----");
    		JqGridPager jqGridPager = new JqGridPager();
        	String where =getWhere(null, null, null, null, null, null, null, null, null, null, null);
        	jqGridPager.setWhere(where);
            setPage(getRequest(), jqGridPager);
            jqGridPager.setRows(100);//100条数据
            jqGridPager.setPager(1);
            jqGridPager.setSidx(" ab.sid ");
            jqGridPager.setSord("desc");
            List<Map<String, Object>> list = tOpenLogService.list(jqGridPager);
            if(list!=null){
            	for(Map<String,Object> m:list){
                	if("1".equals(m.get("ktype"))){//副本钥匙
                		TUsers user = tOpenLogService.getMirrotKeyInfo(Long.valueOf(m.get("ksid").toString()));
                		m.put("ptel", user.getTel());
                		m.put("pname",user.getAuName());
                	}
                	m.put("otime_",m.get("otime").toString().replaceAll("-", "."));
                }
                getRequest().setAttribute("datalist", list);
            }

            log.info("----listView4App end----");
    	}catch(Exception e){
    		log.error(this, e);
    	}
        return SUCCESS;
    }*/
    public String listView4App() {
    	try{
    		log.info("----listView4App start----");
    		JqGridPager jqGridPager = new JqGridPager();
        	String where =getWhere(null, null, null, null, null, null, null, null, null, null, null);
        	jqGridPager.setWhere(where);
            setPage(getRequest(), jqGridPager);
            jqGridPager.setRows(100);//100条数据
            jqGridPager.setPager(1);
            jqGridPager.setSidx(" ab.otime ");
            jqGridPager.setSord("desc");
            List<Map<String, Object>> list = tOpenLogService.list(jqGridPager);
            List datalist = new ArrayList();
            Map dataMap = new HashMap();
            if(list!=null){
            	String preDate=null;
            	for(Map<String,Object> m:list){
            		String otime = (String)m.get("otime");
            		Date otime_ = DateUtils.stringToDate(otime, "yyyy-MM-dd HH:mm:ss");
            		String odate = DateUtils.formatDate(otime_);
            		m.put("time_",DateUtils.formatTime(otime_));
            		if(odate.equals(preDate)){//把同一天的开门的日志放在一起
            			((List)dataMap.get("list")).add(m);
            		}else{
            			preDate = odate;
            			dataMap = new HashMap();
            			dataMap.put("date", odate);
            			List dlist= new ArrayList();
            			dlist.add(m);
            			dataMap.put("list",dlist );
            			datalist.add(dataMap);
            		}

                	//if("1".equals(m.get("ktype"))){//副本钥匙
                		/*TUsers user = tOpenLogService.getMirrotKeyInfo(Long.valueOf(m.get("ksid").toString()));
                		m.put("ptel", user.getTel());
                		m.put("pname",user.getAuName());*/
                	//}
                	//m.put("otime_",m.get("otime").toString().replaceAll("-", "."));
                }
                getRequest().setAttribute("datalist", datalist);
            }

            log.info("----listView4App end----");
    	}catch(Exception e){
    		log.error(this, e);
    	}
        return SUCCESS;
    }

    private String getWhere(String agtCode, String communityId, String cityCode, String ptimeStart1, String ptimeEnd1, String userName,
			String type, String cbName, String tel, String userId, String pid) {
    	Sysopt  user= (Sysopt)getSession().getAttribute("user");
    	int userRole =  (Integer) getSession().getAttribute("userRole");
    	StringBuilder where = new StringBuilder(" 1=1 ");
    	if (userRole == 1 || userRole == 2 || userRole == 21) {
    		if (!StringUtils.isBlank(agtCode)) {
                where.append(" and ab.agtCode = '");
                where.append(agtCode);
                where.append("'");
            }
        	if (StringUtils.isNotBlank(communityId)) {
        		where.append(" and ab.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
        	if (userRole == 21) {
    			where.append(" and ab.sysoptId =");
    			where.append(user.getSid());
			}
		}else	if (userRole == 3 || userRole == 4) {
			where.append(" and ab.result='1' ");
			where.append(" and ab.agtCode ='");
			where.append(user.getAgtCode());
			where.append("'");
			if (StringUtils.isNotBlank(communityId)) {
        		where.append(" and ab.communityId = '");
        		where.append(communityId);
        		where.append("'");
        	}
		}else if (userRole == 5 || userRole == 6) {
			where.append(" and ab.result='1' ");
    		where.append(" and ab.communityId ='");
    		where.append(user.getCommunityId());
    		where.append("'");
    		if (user.getrLevel()==4) {
    			where.append(" and (ab.status is null or ab.status !=1) ");
			}
    	}

    	if (StringUtils.isNotBlank(cityCode)) {
    		where.append(" and ab.cityCode like'%");
    		where.append(cityCode);
    		where.append("%'");
    	}
    	if (!StringUtils.isBlank(ptimeStart1)) {
    		where.append(" and ab.otime1 >= to_date('");
    		where.append(ptimeStart1);
    		where.append("','yyyy-mm-dd hh24:mi:ss')");
    	}
    	if (!StringUtils.isBlank(ptimeEnd1)) {
    		where.append(" and ab.otime1 <= to_date('");
    		where.append(ptimeEnd1);
    		where.append("','yyyy-mm-dd hh24:mi:ss')");
    	}
    	if (StringUtils.isNotBlank(userName)) {
    		where.append(" and ab.auname like'%");
    		where.append(userName);
    		where.append("%'");
    	}
    	if (StringUtils.isNotBlank(type)) {
//    		if("2".equals(type)){						//todo Updated by Saber on 2017/7/27 下午4:19
//    			where.append(" and ab.opentype ='");
//    		}else{
//    			where.append(" and ab.opentype !='");
//    		}
//    		where.append("2'");
			where.append(" and ab.opentype ='");		//todo Created by Saber on 2017/7/27 下午4:19
			where.append(type);
			where.append("'");
    	}
    	if (StringUtils.isNotBlank(cbName)) {
    		where.append(" and ab.installName like'%");
    		where.append(cbName);
    		where.append("%'");
    	}
    	if (StringUtils.isNotBlank(tel)) {
    		where.append(" and ab.tel='");
    		where.append(tel);
    		where.append("'");
    	}
    	if (StringUtils.isNotBlank(userId)) {
    		where.append(" and ab.aUid='");
    		where.append(userId);
    		where.append("'");
    	}
    	if (StringUtils.isNotBlank(pid)) {
    		where.append(" and ab.pid='");
    		where.append(pid);
    		where.append("'");
    	}
    	return where.toString();
	}
    public void exportExcelCheck() throws Exception {
		result = new HashMap<String, Object>();
		String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String cityCode = getRequest().getParameter("cityCode");
    	String ptimeStart1 = getRequest().getParameter("ptimeStart1");
    	String ptimeEnd1 = getRequest().getParameter("ptimeEnd1");
    	String userName = getRequest().getParameter("userName");
    	String type = getRequest().getParameter("type");
    	String cbName = getRequest().getParameter("cbName");
    	String tel = getRequest().getParameter("tel");
    	String userId = getRequest().getParameter("userId");
    	String pid = getRequest().getParameter("pid");

    	String where  = getWhere(agtCode,communityId,cityCode,ptimeStart1,ptimeEnd1,userName,type,cbName,tel,userId,pid);
    	List<Map<String, Object>> tOpenLog = tOpenLogService.exportExcelList(where);
    	if (tOpenLog.size()>20000) {
    		result.put("code", 0);
    		result.put("msg", "日志数量大于2万，请查询后缩小范围");
		}else{
			result.put("code", 1);
    		result.put("msg", "正在导出，请稍候，日志数量："+tOpenLog.size()+" 条");
		}
    	responseBody(result);
    }

	public String exportExcel() throws Exception {
		result = new HashMap<String, Object>();
		String agtCode = getRequest().getParameter("agtCode");
    	String communityId = getRequest().getParameter("communityId");
    	String cityCode = getRequest().getParameter("cityCode");
    	if("undefined".equals(cityCode)){
    		cityCode=null;
    	}
    	String ptimeStart1 = getRequest().getParameter("ptimeStart1");
    	String ptimeEnd1 = getRequest().getParameter("ptimeEnd1");
    	String userName = getRequest().getParameter("userName");
    	String type = getRequest().getParameter("type");
    	String cbName = getRequest().getParameter("cbName");
    	String tel = getRequest().getParameter("tel");
    	String userId = getRequest().getParameter("userId");
    	String pid = getRequest().getParameter("pid");

    	String where  = getWhere(agtCode,communityId,cityCode,ptimeStart1,ptimeEnd1,userName,type,cbName,tel,userId,pid);
    	List<Map<String, Object>> tOpenLog = tOpenLogService.exportExcelList(where);
    	String sheetname  = "开门日志";
        LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
        map.put("CITYCODE" ,"所属区域");
        map.put( "AGTNAME" ,"公司");
        map.put("COMMUNITYNAME" ,"小区");
        map.put("OPENTYPE1" ,"来源");
        map.put("INSTALLNAME" ,"门禁名称");
        map.put("AUNAME" ,"姓名");
        map.put("TEL" ,"手机号");
        map.put("OTIME" ,"开门时间");
        String[] uniqueFields = {"手机号","姓名"};
        HttpServletResponse response = getResponse();
    	ExcelUtil.listToExcel(tOpenLog, map, sheetname, 65535,response);
    	return null;
    }
    private TOpenLog tOpenLog = new TOpenLog();

    @Override
    public TOpenLog getModel() {
        return tOpenLog;
    }
}
